package pageShare

import (
	"context"
	"encoding/json"

	"laundry-service/app/client/internal/svc"
	"laundry-service/app/client/internal/types"

	"github.com/jinzhu/gorm"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetPageShareLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetPageShareLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPageShareLogic {
	return &GetPageShareLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetPageShareLogic) GetPageShare(req *types.GetPageShareRequest) (resp *types.CreatePageShareReply, err error) {
	userId, _ := l.ctx.Value("userId").(json.Number).Int64()
	_, err = l.svcCtx.Db.GetAdminById(int(userId))
	if err != nil {
		return nil, err
	}

	pageShare, err := l.svcCtx.Db.GetPageShareByPath(req.Path)
	if err != nil && gorm.IsRecordNotFoundError(err) {
		return nil, nil
	}

	return &types.CreatePageShareReply{
		Id:          pageShare.ID,
		CreatedAt:   pageShare.CreatedAt.Format("2006-01-02 15:04:05"),
		UpdatedAt:   pageShare.UpdatedAt.Format("2006-01-02 15:04:05"),
		Path:        pageShare.Path,
		Title:       pageShare.Title,
		Description: pageShare.Description,
		ImageUrl:    pageShare.ImageUrl,
	}, err
}
